

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="叶飞">
  <meta name="keywords" content="">
  
    <meta name="description" content="转载：RESTful API 最佳实践 - 阮一峰的网络日志 (ruanyifeng.com)   一、URL 设计  1.1 动词 + 宾语 RESTful 的核心思想就是，客户端发出的数据操作指令都是&quot;动词 + 宾语&quot;的结构。比如，GET &#x2F;articles这个命令，GET是动词，&#x2F;articles是宾语。 动词通常就是五种 HTTP 方法，对应 CRUD 操作。   G">
<meta property="og:type" content="article">
<meta property="og:title" content="Restful实践">
<meta property="og:url" content="http://example.com/2022/04/17/20220417-Restful/index.html">
<meta property="og:site_name" content="博客">
<meta property="og:description" content="转载：RESTful API 最佳实践 - 阮一峰的网络日志 (ruanyifeng.com)   一、URL 设计  1.1 动词 + 宾语 RESTful 的核心思想就是，客户端发出的数据操作指令都是&quot;动词 + 宾语&quot;的结构。比如，GET &#x2F;articles这个命令，GET是动词，&#x2F;articles是宾语。 动词通常就是五种 HTTP 方法，对应 CRUD 操作。   G">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-04-17T13:48:59.000Z">
<meta property="article:modified_time" content="2022-04-17T13:51:20.993Z">
<meta property="article:author" content="叶飞">
<meta property="article:tag" content="Restful">
<meta name="twitter:card" content="summary_large_image">
  
  
  
  <title>Restful实践 - 博客</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>No Tomorrow</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Restful实践"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        叶飞
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-04-17 21:48" pubdate>
          星期日, 四月 17日 2022, 9:48 晚上
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          <!-- compatible with older versions-->
          4.5k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          <!-- compatible with older versions-->
          38 分钟
        
      </span>
    

    
    
      
        <span id="leancloud-page-views-container" class="post-meta" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="leancloud-page-views"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Restful实践</h1>
            
            
              <div class="markdown-body">
                
                <blockquote>
<p>转载：<a target="_blank" rel="noopener" href="http://www.ruanyifeng.com/blog/2018/10/restful-api-best-practices.html">RESTful API 最佳实践 - 阮一峰的网络日志 (ruanyifeng.com)</a></p>
</blockquote>
<h2 id="一-url-设计"><a class="markdownIt-Anchor" href="#一-url-设计"></a> 一、URL 设计</h2>
<h3 id="11-动词-宾语"><a class="markdownIt-Anchor" href="#11-动词-宾语"></a> 1.1 动词 + 宾语</h3>
<p>RESTful 的核心思想就是，客户端发出的数据操作指令都是&quot;动词 + 宾语&quot;的结构。比如，<code>GET /articles</code>这个命令，<code>GET</code>是动词，<code>/articles</code>是宾语。</p>
<p>动词通常就是五种 HTTP 方法，对应 CRUD 操作。</p>
<blockquote>
<ul>
<li>GET：读取（Read）</li>
<li>POST：新建（Create）</li>
<li>PUT：更新（Update）</li>
<li>PATCH：更新（Update），通常是部分更新</li>
<li>DELETE：删除（Delete）</li>
</ul>
</blockquote>
<p>根据 HTTP 规范，动词一律大写。</p>
<h3 id="12-动词的覆盖"><a class="markdownIt-Anchor" href="#12-动词的覆盖"></a> 1.2 动词的覆盖</h3>
<p>有些客户端只能使用<code>GET</code>和<code>POST</code>这两种方法。服务器必须接受<code>POST</code>模拟其他三个方法（<code>PUT</code>、<code>PATCH</code>、<code>DELETE</code>）。</p>
<p>这时，客户端发出的 HTTP 请求，要加上<code>X-HTTP-Method-Override</code>属性，告诉服务器应该使用哪一个动词，覆盖<code>POST</code>方法。</p>
<blockquote>
<figure class="highlight http"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs http">POST /api/Person/4 HTTP/1.1  <br><span class="hljs-attribute">X-HTTP-Method-Override</span><span class="hljs-punctuation">: </span>PUT<br></code></pre></td></tr></table></figure>
</blockquote>
<p>上面代码中，<code>X-HTTP-Method-Override</code>指定本次请求的方法是<code>PUT</code>，而不是<code>POST</code>。</p>
<h3 id="13-宾语必须是名词"><a class="markdownIt-Anchor" href="#13-宾语必须是名词"></a> 1.3 宾语必须是名词</h3>
<p>宾语就是 API 的 URL，是 HTTP 动词作用的对象。它应该是名词，不能是动词。比如，<code>/articles</code>这个 URL 就是正确的，而下面的 URL 不是名词，所以都是错误的。</p>
<blockquote>
<ul>
<li>/getAllCars</li>
<li>/createNewCar</li>
<li>/deleteAllRedCars</li>
</ul>
</blockquote>
<h3 id="14-复数-url"><a class="markdownIt-Anchor" href="#14-复数-url"></a> 1.4 复数 URL</h3>
<p>既然 URL 是名词，那么应该使用复数，还是单数？</p>
<p>这没有统一的规定，但是常见的操作是读取一个集合，比如<code>GET /articles</code>（读取所有文章），这里明显应该是复数。</p>
<p>为了统一起见，建议都使用复数 URL，比如<code>GET /articles/2</code>要好于<code>GET /article/2</code>。</p>
<h3 id="15-避免多级-url"><a class="markdownIt-Anchor" href="#15-避免多级-url"></a> 1.5 避免多级 URL</h3>
<p>常见的情况是，资源需要多级分类，因此很容易写出多级的 URL，比如获取某个作者的某一类文章。</p>
<blockquote>
<figure class="highlight http"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs http">GET /authors/12/categories/2<br></code></pre></td></tr></table></figure>
</blockquote>
<p>这种 URL 不利于扩展，语义也不明确，往往要想一会，才能明白含义。</p>
<p>更好的做法是，除了第一级，其他级别都用查询字符串表达。</p>
<blockquote>
<figure class="highlight http"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs http">GET /authors/12?categories=2<br></code></pre></td></tr></table></figure>
</blockquote>
<p>下面是另一个例子，查询已发布的文章。你可能会设计成下面的 URL。</p>
<blockquote>
<figure class="highlight http"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs http">GET /articles/published<br></code></pre></td></tr></table></figure>
</blockquote>
<p>查询字符串的写法明显更好。</p>
<blockquote>
<figure class="highlight http"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs http">GET /articles?published=true<br></code></pre></td></tr></table></figure>
</blockquote>
<h2 id="二-状态码"><a class="markdownIt-Anchor" href="#二-状态码"></a> 二、状态码</h2>
<h3 id="21-状态码必须精确"><a class="markdownIt-Anchor" href="#21-状态码必须精确"></a> 2.1 状态码必须精确</h3>
<p>客户端的每一次请求，服务器都必须给出回应。回应包括 HTTP 状态码和数据两部分。</p>
<p>HTTP 状态码就是一个三位数，分成五个类别。</p>
<blockquote>
<ul>
<li><code>1xx</code>：相关信息</li>
<li><code>2xx</code>：操作成功</li>
<li><code>3xx</code>：重定向</li>
<li><code>4xx</code>：客户端错误</li>
<li><code>5xx</code>：服务器错误</li>
</ul>
</blockquote>
<p>这五大类总共包含<a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/List_of_HTTP_status_codes">100多种</a>状态码，覆盖了绝大部分可能遇到的情况。每一种状态码都有标准的（或者约定的）解释，客户端只需查看状态码，就可以判断出发生了什么情况，所以服务器应该返回尽可能精确的状态码。</p>
<p>API 不需要<code>1xx</code>状态码，下面介绍其他四类状态码的精确含义。</p>
<h3 id="22-2xx-状态码"><a class="markdownIt-Anchor" href="#22-2xx-状态码"></a> 2.2 2xx 状态码</h3>
<p><code>200</code>状态码表示操作成功，但是不同的方法可以返回更精确的状态码。</p>
<blockquote>
<ul>
<li>GET: 200 OK</li>
<li>POST: 201 Created</li>
<li>PUT: 200 OK</li>
<li>PATCH: 200 OK</li>
<li>DELETE: 204 No Content</li>
</ul>
</blockquote>
<p>上面代码中，<code>POST</code>返回<code>201</code>状态码，表示生成了新的资源；<code>DELETE</code>返回<code>204</code>状态码，表示资源已经不存在。</p>
<p>此外，<code>202 Accepted</code>状态码表示服务器已经收到请求，但还未进行处理，会在未来再处理，通常用于异步操作。下面是一个例子。</p>
<blockquote>
<figure class="highlight http"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs http"><span class="hljs-meta">HTTP/1.1</span> <span class="hljs-number">202</span> Accepted<br><br><span class="language-json"><span class="hljs-punctuation">&#123;</span></span><br><span class="language-json">  <span class="hljs-attr">&quot;task&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span></span><br><span class="language-json">    <span class="hljs-attr">&quot;href&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;/api/company/job-management/jobs/2130040&quot;</span><span class="hljs-punctuation">,</span></span><br><span class="language-json">    <span class="hljs-attr">&quot;id&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;2130040&quot;</span></span><br><span class="language-json">  <span class="hljs-punctuation">&#125;</span></span><br><span class="language-json"><span class="hljs-punctuation">&#125;</span></span><br></code></pre></td></tr></table></figure>
</blockquote>
<h3 id="23-3xx-状态码"><a class="markdownIt-Anchor" href="#23-3xx-状态码"></a> 2.3 3xx 状态码</h3>
<p>API 用不到<code>301</code>状态码（永久重定向）和<code>302</code>状态码（暂时重定向，<code>307</code>也是这个含义），因为它们可以由应用级别返回，浏览器会直接跳转，API 级别可以不考虑这两种情况。</p>
<p>API 用到的<code>3xx</code>状态码，主要是<code>303 See Other</code>，表示参考另一个 URL。它与<code>302</code>和<code>307</code>的含义一样，也是&quot;暂时重定向&quot;，区别在于<code>302</code>和<code>307</code>用于<code>GET</code>请求，而<code>303</code>用于<code>POST</code>、<code>PUT</code>和<code>DELETE</code>请求。收到<code>303</code>以后，浏览器不会自动跳转，而会让用户自己决定下一步怎么办。下面是一个例子。</p>
<blockquote>
<figure class="highlight http"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs http"><span class="hljs-meta">HTTP/1.1</span> <span class="hljs-number">303</span> See Other<br><span class="hljs-attribute">Location</span><span class="hljs-punctuation">: </span>/api/orders/12345<br></code></pre></td></tr></table></figure>
</blockquote>
<h3 id="24-4xx-状态码"><a class="markdownIt-Anchor" href="#24-4xx-状态码"></a> 2.4 4xx 状态码</h3>
<p><code>4xx</code>状态码表示客户端错误，主要有下面几种。</p>
<p><code>400 Bad Request</code>：服务器不理解客户端的请求，未做任何处理。</p>
<p><code>401 Unauthorized</code>：用户未提供身份验证凭据，或者没有通过身份验证。</p>
<p><code>403 Forbidden</code>：用户通过了身份验证，但是不具有访问资源所需的权限。</p>
<p><code>404 Not Found</code>：所请求的资源不存在，或不可用。</p>
<p><code>405 Method Not Allowed</code>：用户已经通过身份验证，但是所用的 HTTP 方法不在他的权限之内。</p>
<p><code>410 Gone</code>：所请求的资源已从这个地址转移，不再可用。</p>
<p><code>415 Unsupported Media Type</code>：客户端要求的返回格式不支持。比如，API 只能返回 JSON 格式，但是客户端要求返回 XML 格式。</p>
<p><code>422 Unprocessable Entity</code> ：客户端上传的附件无法处理，导致请求失败。</p>
<p><code>429 Too Many Requests</code>：客户端的请求次数超过限额。</p>
<h3 id="25-5xx-状态码"><a class="markdownIt-Anchor" href="#25-5xx-状态码"></a> 2.5 5xx 状态码</h3>
<p><code>5xx</code>状态码表示服务端错误。一般来说，API 不会向用户透露服务器的详细信息，所以只要两个状态码就够了。</p>
<p><code>500 Internal Server Error</code>：客户端请求有效，服务器处理时发生了意外。</p>
<p><code>503 Service Unavailable</code>：服务器无法处理请求，一般用于网站维护状态。</p>
<h2 id="三-服务器回应"><a class="markdownIt-Anchor" href="#三-服务器回应"></a> 三、服务器回应</h2>
<h3 id="31-不要返回纯本文"><a class="markdownIt-Anchor" href="#31-不要返回纯本文"></a> 3.1 不要返回纯本文</h3>
<p>API 返回的数据格式，不应该是纯文本，而应该是一个 JSON 对象，因为这样才能返回标准的结构化数据。所以，服务器回应的 HTTP 头的<code>Content-Type</code>属性要设为<code>application/json</code>。</p>
<p>客户端请求时，也要明确告诉服务器，可以接受 JSON 格式，即请求的 HTTP 头的<code>ACCEPT</code>属性也要设成<code>application/json</code>。下面是一个例子。</p>
<blockquote>
<figure class="highlight http"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs http">GET /orders/2 HTTP/1.1 <br><span class="hljs-attribute">Accept</span><span class="hljs-punctuation">: </span>application/json<br></code></pre></td></tr></table></figure>
</blockquote>
<h3 id="32-发生错误时不要返回-200-状态码"><a class="markdownIt-Anchor" href="#32-发生错误时不要返回-200-状态码"></a> 3.2 发生错误时，不要返回 200 状态码</h3>
<p>有一种不恰当的做法是，即使发生错误，也返回<code>200</code>状态码，把错误信息放在数据体里面，就像下面这样。</p>
<blockquote>
<figure class="highlight http"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs http"><span class="hljs-meta">HTTP/1.1</span> <span class="hljs-number">200</span> OK<br><span class="hljs-attribute">Content-Type</span><span class="hljs-punctuation">: </span>application/json<br><br><span class="language-smalltalk">&#123;</span><br><span class="language-smalltalk">  <span class="hljs-comment">&quot;status&quot;</span>: <span class="hljs-comment">&quot;failure&quot;</span>,</span><br><span class="language-smalltalk">  <span class="hljs-comment">&quot;data&quot;</span>: &#123;</span><br><span class="language-smalltalk">    <span class="hljs-comment">&quot;error&quot;</span>: <span class="hljs-comment">&quot;Expected at least two items in list.&quot;</span></span><br><span class="language-smalltalk">  &#125;</span><br><span class="language-smalltalk">&#125;</span><br></code></pre></td></tr></table></figure>
</blockquote>
<p>上面代码中，解析数据体以后，才能得知操作失败。</p>
<p>这张做法实际上取消了状态码，这是完全不可取的。正确的做法是，状态码反映发生的错误，具体的错误信息放在数据体里面返回。下面是一个例子。</p>
<blockquote>
<figure class="highlight http"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs http"><span class="hljs-meta">HTTP/1.1</span> <span class="hljs-number">400</span> Bad Request<br><span class="hljs-attribute">Content-Type</span><span class="hljs-punctuation">: </span>application/json<br><br><span class="language-json"><span class="hljs-punctuation">&#123;</span></span><br><span class="language-json">  <span class="hljs-attr">&quot;error&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;Invalid payoad.&quot;</span><span class="hljs-punctuation">,</span></span><br><span class="language-json">  <span class="hljs-attr">&quot;detail&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">&#123;</span></span><br><span class="language-json">     <span class="hljs-attr">&quot;surname&quot;</span><span class="hljs-punctuation">:</span> <span class="hljs-string">&quot;This field is required.&quot;</span></span><br><span class="language-json">  <span class="hljs-punctuation">&#125;</span></span><br><span class="language-json"><span class="hljs-punctuation">&#125;</span></span><br></code></pre></td></tr></table></figure>
</blockquote>
<h3 id="33-提供链接"><a class="markdownIt-Anchor" href="#33-提供链接"></a> 3.3 提供链接</h3>
<p>API 的使用者未必知道，URL 是怎么设计的。一个解决方法就是，在回应中，给出相关链接，便于下一步操作。这样的话，用户只要记住一个 URL，就可以发现其他的 URL。这种方法叫做 HATEOAS。</p>
<p>举例来说，GitHub 的 API 都在 <a target="_blank" rel="noopener" href="https://api.github.com/">api.github.com</a> 这个域名。访问它，就可以得到其他 URL。</p>
<blockquote>
<figure class="highlight http"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs http">&#123;<br>  ...<br>  &quot;feeds_url&quot;: &quot;https://api.github.com/feeds&quot;,<br>  &quot;followers_url&quot;: &quot;https://api.github.com/user/followers&quot;,<br>  &quot;following_url&quot;: &quot;https://api.github.com/user/following&#123;/target&#125;&quot;,<br>  &quot;gists_url&quot;: &quot;https://api.github.com/gists&#123;/gist_id&#125;&quot;,<br>  &quot;hub_url&quot;: &quot;https://api.github.com/hub&quot;,<br>  ...<br>&#125;<br></code></pre></td></tr></table></figure>
</blockquote>
<p>上面的回应中，挑一个 URL 访问，又可以得到别的 URL。对于用户来说，不需要记住 URL 设计，只要从 <a target="_blank" rel="noopener" href="http://api.github.com">api.github.com</a> 一步步查找就可以了。</p>
<p>HATEOAS 的格式没有统一规定，上面例子中，GitHub 将它们与其他属性放在一起。更好的做法应该是，将相关链接与其他属性分开。</p>
<blockquote>
<figure class="highlight http"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs http"><span class="hljs-meta">HTTP/1.1</span> <span class="hljs-number">200</span> OK<br><span class="hljs-attribute">Content-Type</span><span class="hljs-punctuation">: </span>application/json<br><br><span class="language-prolog">&#123;</span><br><span class="language-prolog">  <span class="hljs-string">&quot;status&quot;</span>: <span class="hljs-string">&quot;In progress&quot;</span>,</span><br><span class="language-prolog">   <span class="hljs-string">&quot;links&quot;</span>: &#123;[</span><br><span class="language-prolog">    &#123; <span class="hljs-string">&quot;rel&quot;</span>:<span class="hljs-string">&quot;cancel&quot;</span>, <span class="hljs-string">&quot;method&quot;</span>: <span class="hljs-string">&quot;delete&quot;</span>, <span class="hljs-string">&quot;href&quot;</span>:<span class="hljs-string">&quot;/api/status/12345&quot;</span> &#125; ,</span><br><span class="language-prolog">    &#123; <span class="hljs-string">&quot;rel&quot;</span>:<span class="hljs-string">&quot;edit&quot;</span>, <span class="hljs-string">&quot;method&quot;</span>: <span class="hljs-string">&quot;put&quot;</span>, <span class="hljs-string">&quot;href&quot;</span>:<span class="hljs-string">&quot;/api/status/12345&quot;</span> &#125;</span><br><span class="language-prolog">  ]&#125;</span><br><span class="language-prolog">&#125;</span><br></code></pre></td></tr></table></figure>
</blockquote>
<h2 id="四-参考链接"><a class="markdownIt-Anchor" href="#四-参考链接"></a> 四、参考链接</h2>
<ul>
<li><a target="_blank" rel="noopener" href="https://blog.florimondmanca.com/restful-api-design-13-best-practices-to-make-your-users-happy">RESTful API Design: 13 Best Practices to Make Your Users Happy</a>, by Florimond Manca</li>
<li><a target="_blank" rel="noopener" href="https://docs.microsoft.com/en-us/azure/architecture/best-practices/api-design">API design</a>, by MicroSoft Azure</li>
</ul>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E7%BD%91%E7%BB%9C/" class="category-chain-item">网络</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/Restful/">#Restful</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Restful实践</div>
      <div>http://example.com/2022/04/17/20220417-Restful/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>叶飞</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年4月17日</div>
        </div>
      
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/04/17/20220417-Gin%E5%8A%A8%E6%80%81%E8%B7%AF%E7%94%B1/" title="Gin动态路由">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Gin动态路由</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/04/14/20220414-%E5%AE%89%E8%A3%85RabbitMQ/" title="安装RabbitMQ">
                        <span class="hidden-mobile">安装RabbitMQ</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  


  
  









    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  
      <script>
        if (!window.MathJax) {
          window.MathJax = {
            tex    : {
              inlineMath: { '[+]': [['$', '$']] }
            },
            loader : {
              load: ['ui/lazy']
            },
            options: {
              renderActions: {
                insertedScript: [200, () => {
                  document.querySelectorAll('mjx-container').forEach(node => {
                    let target = node.parentNode;
                    if (target.nodeName.toLowerCase() === 'li') {
                      target.parentNode.classList.add('has-jax');
                    }
                  });
                }, '', false]
              }
            }
          };
        } else {
          MathJax.startup.document.state(0);
          MathJax.texReset();
          MathJax.typeset();
          MathJax.typesetPromise();
        }
      </script>
    

  <script  src="https://lib.baomitu.com/mathjax/3.2.1/es5/tex-mml-chtml.js" ></script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="/js/leancloud.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
